<?php
namespace app\kaoqin\api;

use api\auth\Token;
use app\common\logic\User;
use think\Session;
use my\wechat\QyWeChat;

class Open extends Common
{
    protected $_needCheckUser = false;
    protected $_needCheckToken = false;

    private $_wechat = null;

    private function wechat()
    {
        $c = [
            'appid' => c('wx_appid'),
            'appsecret' => c('wx_appsecret')
        ];

        if ($this->_wechat == null)
            $this->_wechat = new QyWeChat($c);

        return $this->_wechat;
    }

    /**
     * 模拟登录
     * @return array
     * @author wb <pithyone@vip.qq.com>
     */
    public function login()
    {
        // 验证微信附加的code参数
        $code = input('code');
        // 根据系统环境跳转到相关的验证页面
        if (config('app_is_release') && !empty($code)) {
            $data = $this->weChatLogin($code);
        } else {
            $data = $this->cheatLogin();
        }

        // 错误情况
        if ($data === false) {
            return $this->error($this->_error);
        }

        $user_id = $data['user_id'];
        $timeout = $data['timeout'];

        // 存Session
        Session::set('uid', $user_id);

        // 配置
        $config = $this->config($timeout);

        $ret = [
            'config' => $config,
            'user_info' => User::where(['userid' => $user_id])->find()
        ];

        return $this->success($ret);
    }

    private function config($timeout = 604800)
    {
        $config['access'] = session_id();

        $uid = function_exists('getUid') ? getUid() : '';
        $token = Token::update_token($uid, $timeout);
        $config['token'] = $token;

        $res = config("app_res");
        if (!empty($res)) $config['res'] = $res;

        $is_release = config("app_is_release");
        if (!$is_release) $config['debug'] = true;

        return $config;
    }

    /**
     * 模拟登陆
     * @return array|bool
     * @author wb <pithyone@vip.qq.com>
     */
    private function cheatLogin()
    {
        // 参数&验证
        $user = input('uid');
        $password = input('password');
        if (!(!empty($user) && !empty($password))) {

            $this->_error = '用户名、密码不能同时为空';
            return false;
        }

        if (config('app_is_release')) {
            if ($password != date('Ymd')) {

                $this->_error = '密码错误';
                return false;
            }
        }

        // 超时时间，如果是已经注册的用户，模拟微信返回UserId，如果是未注册用户，模拟微信返回OpenId
        $timeout = User::where(['userid' => $user])->find() ? 3600 * 24 * 7 : 1;
        $ret = ['user_id' => $user, 'timeout' => $timeout];

        return $ret;
    }

    /**
     * 根据code获取成员信息
     * @param $code
     * @return array|bool
     * @author wb <pithyone@vip.qq.com>
     */
    private function weChatLogin($code)
    {
        // 获取成员
        $user = $this->wechat()->getUserId($code);

        if (isset($user['UserId'])) { // 已关注
            // 返回信息
            $user_id = $user['UserId'];
            $ret = ['user_id' => $user_id, 'timeout' => 3600 * 24 * 7];
        } else if (isset($user['OpenId'])) { // 未关注
            // 返回信息
            $user_id = $user['OpenId'];
            $ret = ['user_id' => $user_id, 'timeout' => 1];
        } else { // 出现错误
            $this->_error = '微信登陆失败';
            return false;
        }

        return $ret;
    }

    /**
     * 微信OAuth授权
     * @return \think\response\Redirect
     * @author wb <pithyone@vip.qq.com>
     */
    public function oauth()
    {
        $protocol = input('server.https') ? 'https:' : 'http:';
        $url = $protocol . '//' . input('host') . '/kaoqin/open/login.html';
        // 根据系统环境跳转到相关的验证页面
        if (config('app_is_release')) {
            $redirect_url = $this->wechat()->getOauthRedirect($url);
            return redirect($redirect_url);
        } else {
            return redirect($url);
        }
    }
}